package com.bilibili.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bilibili.entity.Comment;
import com.bilibili.service.CommentService;
import com.bilibili.service.impl.CommentServiceImpl;

@WebServlet("/threeComment.do")
public class ThreeCommentServlet extends HttpServlet {
    private static final int LATEST_COMMENT_LIMIT = 3; // 限制返回的最新评论数量
    private CommentService cs = new CommentServiceImpl();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        
        try {
            // 1. 从请求参数获取视频ID
            String videoIdStr = request.getParameter("e");
            int videoId = (videoIdStr != null && !videoIdStr.isEmpty()) 
                ? Integer.parseInt(videoIdStr) 
                : 0; // 默认值或抛出异常
            
            if (videoId == 0) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"error\":\"Video ID is required\"}");
                return;
            }
            
            // 2. 获取该视频的所有评论（已按时间倒序排列）
            List<Comment> comments = cs.selectAllByVId(videoId);
            
            // 3. 限制返回数量（数据库查询已通过LIMIT 3限制，此处可省略排序）
            if(comments.size() > LATEST_COMMENT_LIMIT) {
                comments = comments.subList(0, LATEST_COMMENT_LIMIT);
            }
            
            // 4. 返回结果（假设CommenResult是正确的响应实体）
            response.getWriter().write(convertToJson(comments));
            
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("{\"error\":\"Invalid video ID\"}");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"error\":\"Server error\"}");
        }
    }
    
    // 辅助方法：将评论列表转换为JSON字符串
    private String convertToJson(List<Comment> comments) {
        // 实际项目中应使用JSON库（如Gson、Jackson）
        StringBuilder sb = new StringBuilder();
        sb.append("{\"data\":[");
        for (int i = 0; i < comments.size(); i++) {
            Comment c = comments.get(i);
            sb.append("{");
            sb.append("\"commentId\":").append(c.getCommentId()).append(",");
            sb.append("\"videoId\":").append(c.getVideoId()).append(",");
            sb.append("\"userId\":").append(c.getUserId()).append(",");
            sb.append("\"content\":\"").append(c.getContent()).append("\",");
            sb.append("\"createTime\":\"").append(c.getCreateTime()).append("\",");
            sb.append("\"replyTo\":").append(c.getReplyTo() != null ? c.getReplyTo() : "null").append(",");
            sb.append("\"likeCount\":").append(c.getLikeCount()).append(",");
            sb.append("\"username\":\"").append(c.getUsername()).append("\"");
            sb.append("}");
            if (i < comments.size() - 1) sb.append(",");
        }
        sb.append("]}");
        return sb.toString();
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}